set(TOOLCHAIN_PATH $ENV{ARM_GCC_ROOT})

# 提示编译工具链路径
MESSAGE(STATUS "**** Toolchain path: ${TOOLCHAIN_PATH} ****")


# 编译工具链
set(CMAKE_C_COMPILER "arm-none-eabi-gcc.exe")
set(CMAKE_CXX_COMPILER "arm-none-eabi-g++.exe")
set(AS "arm-none-eabi-as.exe")
set(AR "arm-none-eabi-ar.exe")
set(OBJCOPY "arm-none-eabi-objcopy.exe")
set(OBJDUMP "arm-none-eabi-objdump.exe")
set(SIZE "arm-none-eabi-size.exe")

# 使用的 C 语言版本
set(CMAKE_C_STANDARD 11)
# 使用的 cpp 版本
set(CMAKE_CXX_STANDARD 17)
# 生成 compile_commands.json，可配合 clangd 实现精准的代码关联与跳转
set(CMAKE_EXPORT_COMPILE_COMMANDS True)
# 彩色日志输出
set(CMAKE_COLOR_DIAGNOSTICS True)

# 路径查找
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

# this makes the test compiles use static library option so that we don't need to pre-set linker flags and scripts
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

# 包含gcc头文件路径
set(SYSTEM_PATH "-isystem ${TOOLCHAIN_PATH}/arm-none-eabi/include")

# 提示编译器头文件路径
MESSAGE(STATUS "**** Compiler include path: ${SYSTEM_PATH} ****")


# 定义通用编译器参数
# ${MCPU_FLAGS}   处理器内核信息
# ${VFP_FLAGS}    浮点运算单元类型
# ${SYSTEM_PATH}  编译器头文件路径
set(CFCOMMON
    "${MCPU_FLAGS} ${VFP_FLAGS} ${SYSTEM_PATH} --specs=nano.specs --specs=nosys.specs -Wall -fmessage-length=0 -ffunction-sections -fdata-sections"
)

# 定义最快运行速度发行模式的编译参数
set(CMAKE_C_FLAGS_RELEASE "-Os ${CFCOMMON}")
set(CMAKE_CXX_FLAGS_RELEASE "-Os ${CFCOMMON} -fno-exceptions")
set(CMAKE_ASM_FLAGS_RELEASE "${MCPU_FLAGS} ${VFP_FLAGS} -x assembler-with-cpp")

# 定义最小尺寸且包含调试信息的编译参数
set(CMAKE_C_FLAGS_RELWITHDEBINFO "-Os -g ${CFCOMMON}")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-Os -g ${CFCOMMON} -fno-exceptions")
set(CMAKE_ASM_FLAGS_RELWITHDEBINFO "${MCPU_FLAGS} ${VFP_FLAGS} -x assembler-with-cpp")

# 定义最小尺寸的编译参数
set(CMAKE_C_FLAGS_MINSIZEREL "-Os ${CFCOMMON}")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os ${CFCOMMON} -fno-exceptions")
set(CMAKE_ASM_FLAGS_MINSIZEREL "${MCPU_FLAGS} ${VFP_FLAGS} -x assembler-with-cpp")

# 定义调试模式编译参数
set(CMAKE_C_FLAGS_DEBUG "-O0 -g ${CFCOMMON}")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g ${CFCOMMON} -fno-exceptions")
set(CMAKE_ASM_FLAGS_DEBUG "${MCPU_FLAGS} ${VFP_FLAGS} -x assembler-with-cpp")

if("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
    message(STATUS "**** Maximum optimization for speed ****")
elseif("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo")
    message(STATUS "**** Maximum optimization for size, debug info included ****")
elseif("${CMAKE_BUILD_TYPE}" STREQUAL "MinSizeRel")
    message(STATUS "**** Maximum optimization for size ****")
else() # "Debug"
    message(STATUS "**** No optimization, debug info included ****")
endif()
